package name.vaccari.matteo.tai.phonedirectory.network;

import static org.junit.Assert.assertEquals;

import java.io.IOException;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;


public class TcpTest {

	private TcpServer server;

	private void testEchoServerWith(TcpClient client, String string)
		throws IOException {
	
		client.writeLine(string);
		assertEquals(string, client.readLine());
	}

	@Before
	public void setUp() throws Exception {
		server = new TcpServer(1234, new EchoProtocol());
		server.start();
		Thread.sleep(100);
	}
	
	@After
	public void tearDown() throws Exception {
		server.close();
	}
	
	@Test
	public void simple() throws Exception {		
		TcpClient client = new TcpClient("localhost", 1234);
		client.connect();
		
		testEchoServerWith(client, "hello");
		
		client.close();
	}

	@Test
	public void twoConnections() throws Exception {
		TcpClient first = new TcpClient("localhost", 1234);
		first.connect();		
		testEchoServerWith(first, "hello");
		testEchoServerWith(first, "hello again");
		first.close();

		TcpClient second = new TcpClient("localhost", 1234);
		second.connect();
		testEchoServerWith(second, "bla bla");
		second.close();
	}
}
